package x.ovo.wechat.bot.plugin;

import lombok.SneakyThrows;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.dromara.hutool.json.JSONObject;
import org.dromara.hutool.json.JSONUtil;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Map;

@UtilityClass
@Slf4j(topic = "DingDingPush")
public class DingDingPush {

    private static final String URL = "https://oapi.dingtalk.com/robot/send?access_token=";

    public static void push(Map<String, ?> config, OkHttpClient client, String flag, String content) {
        String accessToken = (String) config.get("access_token");
        String secret = (String) config.get("secret");
        JSONObject json = JSONUtil.ofObj()
                .set("msgtype", "text")
                .set("text", JSONUtil.ofObj().set("content", flag + ": " + content));
        Request request = new Request.Builder()
                .url(URL + accessToken)
                .post(RequestBody.create(json.toString(), MediaType.parse("application/json")))
                .build();
        try (Response response = client.newCall(request).execute()) {
            JSONObject object = JSONUtil.parseObj(response.body().string());
            if (object.getInt("errcode") == 0 && object.getStr("errmsg").equals("ok")) {
                log.info("钉钉推送成功");
            } else {
                log.error("钉钉推送失败");
            }
        } catch (IOException e) {
            log.error("钉钉推送失败: {}", e.getMessage());
        }
    }

    @SneakyThrows
    private String caclSignature(Long timestamp, String secret) {
        String stringToSign = timestamp + "\n" + secret;
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
        byte[] signData = mac.doFinal(stringToSign.getBytes(StandardCharsets.UTF_8));
        return URLEncoder.encode(new String(Base64.getEncoder().encode(signData), StandardCharsets.UTF_8), StandardCharsets.UTF_8);
    }

}
